package com.jsoft.jsofted.sys.service.impl;

import com.diboot.core.util.S;
import com.diboot.file.util.HttpHelper;
import com.jsoft.jsofted.framework.utils.FileHelper;
import com.jsoft.jsofted.sys.entity.FileEntity;
import com.jsoft.jsofted.sys.service.FileStorageService;
import com.jsoft.jsofted.sys.vo.UploadFileBean;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

@Service
public class LocalFileStorageServiceImpl implements FileStorageService {

    @Override
    public UploadFileBean upload(MultipartFile file) throws Exception {
        UploadFileBean uploadFileBean = new UploadFileBean();
        // 文件后缀
        String fileUid = S.newUuid();
        String ext = FileHelper.getFileExtByName(file.getOriginalFilename());
        String newFileName = fileUid + "." + ext;
        uploadFileBean.setOriginalFilename(file.getOriginalFilename())
                .setExt(ext)
                .setUuid(fileUid)
                .setFilename(newFileName)
                .setStorageFullPath(FileHelper.saveUploadFile(file, newFileName));
        return uploadFileBean;
    }

    @Override
    public void download(FileEntity uploadFile, HttpServletResponse response) throws Exception {
        HttpHelper.downloadLocalFile(uploadFile.getStoragePath(), uploadFile.getName(), response);
    }
}